'use strict'

require('log-timestamp');
const express = require('express');
const router = express.Router();
const utils = require('../utils/utils');
const index = require('../index');
const config = require('../config');
const model = require('../models/models');
const User = model.user;
const assert = require('assert');
const debug = true;
const Gift = model.gift;
const async = require('async');
const modelUtils = require('../utils/modelUtils');
require('log-timestamp');
var multer = require('multer');
var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, 'images')
  },
  filename: function(req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now());
  }
});
var upload = multer({
  storage: storage
});
var cpUpload = upload.fields([{
  name: 'image',
  maxCount: 1
}, {
  name: 'animImage',
  maxCount: 1
}])

/**
 * @apiVersion 0.1.0
 * @ApiDescription 初始化礼物数据
 * @api{post} /api/uploadgift 初始化礼物数据
 * @apiName uploadgift
 * @apiGroup admin
 *
 * @apiParam {String} name 礼物名称
 * @apiParam {Number} price 价格
 * @apiParam {String} filename 礼物名称的拼音
 * @apiParam {String} image 对应的图片文件
 * @apiParam {String} animImage 对应的gif
 * @apiParam {String} adminsecret 管理员秘钥
 *
 * @apiSuccessExample 成功例子:
 {
   errorCode: 1,
    message: '礼物初始化成功!'
}
 * @apiSuccess {Number} errorCode 返回代码
 * @apiSuccess {String} message 返回信息
 * @apiSuccess {json} data　返回数据实体
 */

router.post('/uploadgift', cpUpload, (req, res) => {
  if(!req.body.adminsecret){
    return res.json({
      errorCode: 0,
      message: 'please provide correct adminsecret'
    });
  } else if(config.adminsecret == req.body.adminsecret){
    var gift = new Gift({
      name: (req.body.name) ? req.body.name : '',
      filename: (req.body.filename) ? req.body.filename : '',
      price: (req.body.price) ? req.body.price : '',
      score: (req.body.score) ? req.body.score : '',
      category: (req.body.category) ? req.body.category : '',
      sort: (req.body.sort) ? req.body.sort : '',
      costType: (req.body.costType) ? req.body.costType : '',
      weight: (req.body.weight) ? req.body.weight : '',
    });
    gift.giftid = gift._id;
    if(req.files['image']){
      var cname = req.files['image'][0];
      if(cname){
        gift.image = 'http://' + config.host + ':' + index.port + '/images?file=' + cname.filename;
      }
    }
    if(req.files['animImage']){
      var aname = req.files['animImage'][0];
      if(aname){
        gift.animImage = 'http://' + config.host + ':' + index.port + '/images?file=' + aname.filename;
      }
    }
    gift.save((err) => {
      if(err){
        console.log("err:::" + err.message);
        return res.json({
          errorCode: 0,
          message: 'database write failure:' + err.message
        });
      }
      res.json({
        errorCode: 1,
        message: '礼物初始化成功!',
      });
    });
  } else {
    res.json({
      errorCode: 0,
      message: 'adminsecret wrong!'
    });
  }
});

/**
 * @apiVersion 0.1.0
 * @ApiDescription 通过礼物id更新礼物数据
 * @api{post} /api/updategiftByid 通过礼物id更新礼物数据
 * @apiName updategiftByid
 * @apiGroup admin
 *
 * @apiParam {String} giftid 礼物id
 * @apiParam {Number} price 礼物价格
 * @apiParam {String} adminsecret 管理员秘钥
 *
 * @apiSuccessExample 成功例子:
 {
   errorCode: 1,
    message: '礼物价格更新成功!'
}
 * @apiSuccess {Number} errorCode 返回代码
 * @apiSuccess {String} message 返回信息
 * @apiSuccess {json} data　返回数据实体
 */
router.post('/updategiftByid', cpUpload, (req, res) => {

  if(!req.body.adminsecret || !req.body.giftid || !req.body.price){
    return res.json({
      errorCode: 0,
      message: 'please provide correct parameters'
    });
  } else if(config.adminsecret == req.body.adminsecret){

    Gift.findOne({
      giftid: req.body.giftid
    }, (err, gift) => {
      if(err){
        throw err;
      } else {
        gift.price = req.body.price;
        gift.save((err) => {
          if(err){
            console.log("err:::" + err.message);
            return res.json({
              errorCode: 0,
              message: 'database write failure:' + err.message
            });
          }
          res.json({
            errorCode: 1,
            message: '礼物价格更新成功!',
          });
        });
      }

    });
  } else {
    res.json({
      errorCode: 0,
      message: 'adminsecret wrong!'
    });
  }
});


/**
 * @apiVersion 0.1.0
 * @ApiDescription 删除当前用户user表中数据
 * @api{post} /api/deleteDocumentByMobile  删除当前用户user表中数据
 * @apiName deleteDocumentByMobile
 * @apiGroup admin
 *
 * @apiParam {String} mobile 手机号
 * @apiParam {Number} secret 秘钥
 * @apiSuccessExample 成功例子:
 {
  errorCode: 1,
  message: '用户xxx删除成功!'
　}
 * @apiSuccess {Number} errorCode 返回代码
 * @apiSuccess {String} message 返回信息
 * @apiSuccess {json} data　返回数据实体
 */
router.post('/deleteDocumentByMobile', upload.array(), (req, res) => {
  var mobile = req.body.mobile;
  var secret = req.body.secret;
  if(config.secret == secret){
    if(mobile){
      User.findOne({
        mobile: req.body.mobile
      }, (err, user) => {
        if(err){
          throw err;
        }
        if(!user){
          return res.json({
            errorCode: 0,
            message: '用户不存在!'
          });
        } else {
          user.remove();
          res.json({
            errorCode: 1,
            message: '用户' + mobile + '删除成功！'
          });
        }
      });

    } else {
      return res.send({
        errorCode: 0,
        message: '请输入手机号码--mobile'
      });
    }
  } else {
    return res.send({
      errorCode: 0,
      message: '非管理人员不可删除数据库中数据！'
    });
  }
});

router.post('/updateResourceId_5b836a789236811ccd8738e7', upload.array(), (req, res) => {
  if(req.body.test){
    const faker = require('faker');
    //model.momentResource.update({type:'text'}, { resourceId: 'moment-' + faker.random.uuid() }, { multi: true }).exec();
    model.videoResource.update({}, {resourceId: 'video-' + faker.random.uuid()}, {multi: true}).exec();
  }
  res.json('ok')
});

/**
 * @apiVersion 0.1.0
 * @ApiDescription 更新资源id
 * @api{post} /api/updateResourceId  更新资源id
 * @apiName updateResourceId
 * @apiGroup admin
 *
 * @apiParam {String} type 类型[moment/video]
 * @apiParam {Number} adminsecret 秘钥
 * @apiSuccessExample 成功例子:
 {
  errorCode: 1,
  message: '所有数据更新成功!'
　}
 * @apiSuccess {Number} errorCode 返回代码
 * @apiSuccess {String} message 返回信息
 * @apiSuccess {json} data　返回数据实体
 */
router.post('/updateResourceId', upload.array(), (req, res) => {
  if(!req.body.adminsecret || config.adminsecret != req.body.adminsecret || !req.body.type){
    return res.json({
      errorCode: 0,
      message: 'please provide correct adminsecret / type'
    });
  }
  var resourceType;
  if(req.body.type == 'moment'){
    resourceType = 'moment';
  }
  else if(req.body.type == 'video'){
    resourceType = 'video';
  }
  switch(resourceType) {
    case 'moment':
      var findResource = modelUtils.resourcelistFind('moment');
      break;
    case 'video':
      findResource = modelUtils.resourcelistFind('video');
      break;
    default:
      throw 'fatal: error303'
  }

  Promise.all([findResource]).then(function(values) {
    var theresource = values[0];
    if(theresource && theresource.length > 0){
      async.each(theresource, function(item, callback) {
        var resourceId;
        if(resourceType == 'moment'){
          resourceId = 'moment-' + item._id;
          item.resourceId = resourceId;
        } else if(resourceType == 'video'){
          resourceId = 'video-' + item._id;
          item.resourceId = resourceId;
        }
        item.save((err) => {
          if(err){
            console.error("err:::" + err.message);
            return res.json({
              errorCode: 0,
              message: 'database write failure:' + err.message
            });
          } else {
            callback(null);
          }
        });

      }, function(err) {
        //所有的异步成功执行完成，err等于null
        res.json({
          errorCode: 1,
          message: '所有数据更新成功！'
        });
      });
    } else {
      res.json({
        errorCode: 1,
        message: 'no data!'
      });
    }
  }).catch(err => {
    console.error('err 102:' + err.message);
    console.error('err 103:' + err.stack);
    var msg = err.message ? err.message : err;
    res.json({errorCode: 0, message: msg})
  });
});

const S3Bucket = require('../config').s3Bucket;
const S3ACL = require('../config').s3ACL;
const AWS = require('aws-sdk');
AWS.config.loadFromPath('config/aws_config.json');
var multerS3 = require('multer-s3');
const subdir = "/abusephotos";
let params = {
  "ACL": S3ACL,
};
var s3 = new AWS.S3({"params": params});
var uploadS3 = multer({
  storage: multerS3({
    s3: s3,
    bucket: S3Bucket + subdir,
    acl: S3ACL,
    contentType: multerS3.AUTO_CONTENT_TYPE,
    contentDisposition: 'inline',
    metadata: function(req, file, cb) {
      cb(null, {fieldname: file.fieldname});
    },
    key: function(req, file, cb) {
      cb(null, Date.now().toString())
    }
  })
})
const AbuseReport = model.abuseReport;
/**
 * @apiVersion 0.1.0
 * @ApiDescription 举报不良信息
 * @api{post} /api/report/submit
 * @apiName abuse report
 * @apiGroup Abuse Report
 * @apiParam {String} content text content of reported
 * @apiParam {String} token reporter's token
 * @apiParam {String} abuseIndex
 * @apiParam {file} [photos] snapshots：max 4
 * @apiSuccessExample :
 {
     "errorCode": 1,
     "message": "abuse report submited"
 }
 * @apiSuccess {Number} errorCode 返回代码。1：成功。0：错误
 * @apiSuccess {String} message 返回信息
 */

router.post('/report/submit', uploadS3.array('photos', 4), (req, res) => {
  let isTest = (req.body.test) ? true : false

  if(!req.body.token){
    return res.json({errorCode: 0, message: 'please input token'}).send();
  }

  modelUtils.userFind_token_userCode_auth(req.body.token)
    .then(me => {
      var aubseRecord = new AbuseReport({
        reporter: me.userCode,
        content: req.body.content,
        reportime: Date.now(),
        photoArray: [],
      });
      let photos = req.files;
      if((!photos || photos.length == 0) && !req.body.content){
        throw 'no content nor photos uploaded'
      }
      photos.forEach(thePhoto => {
        let fn = (thePhoto.mimetype).split('/');
        if(utils.imageFilter(fn[fn.length - 1])){
          if(debug) console.log(thePhoto);
          aubseRecord.photos.push(thePhoto.location);
        }
        else throw 'non image files are not allowed::%s', thePhoto.originalname;
      })

      aubseRecord.save().then(() => {
        res.json({errorCode: 1, message: 'abuse report submited'})
      }).catch(err => {
        return res.json({errorCode: 0, message: 'abuse report submit with error::' + (err.message || err)});
      })

    }).catch(err => {
    return res.json({errorCode: 0, message: 'abuse report submit with error::' + (err.message || err)});
  })

})

/**
 * @apiVersion 0.1.0
 * @ApiDescription apns send notification
 * @api{post} /api/apns
 * @apiName apns send notification
 * @apiGroup apns send notification
 *
 * @apiParam {String} token  token
 * @apiParam {String} sessionId  sessionId
 * @apiParam {String} tokboxToken  tokboxToken
 * @apiParam {int} [platform]  platform default=1: ios, 2:android, 3:winphone, 4:others
 * @apiParam {String} userCode  the user's userCode
 *
 * @apiSuccessExample 验证成功例子:
 {
    "errorCode": 1,
    "message": "Done"
}
 * @apiSuccess {Number} errorCode
 * @apiSuccess {String} message
 */
router.post('/apns', upload.array(), (req, res) => {
  const isTest = (req.body.test) ? true : false;
  const cert = 'show_voip_cert.pem';
  const uuid = require('uuidv4');
  const shell = require('shelljs');
  if(!req.body.token || !req.body.userCode){
    return res.json({errorCode: 0, message: 'please input token,userCode or platform'});
  }
  const platform = req.body.platform || 1;
  var findme = modelUtils.userFind_token_userCode_auth(req.body.token);
  assert.ok(findme instanceof Promise);
  let finduser = modelUtils.userFindAuth(null, req.body.userCode);
  assert.ok(finduser instanceof Promise);
  Promise.all([findme, finduser]).then(function(values) {
    // curl -v -d '{"alert":"hello","uuid": "62e18930-5c18-4aea-b821-61dd3b82d17e","handle":"Show"}' --http2 --cert config/show_voip_cert.pem   https://api.development.push.apple.com/3/device/dccc50ab1098c364b46f74fbab26d4bf3b7bdcf4b04778c03df6002f9fa1a4fb
    let me = values[0], user = values[1];
    // let cert = "show_voip_cert.pem";
    let appleURL = 'https://api.development.push.apple.com/3/device/' + user.device.devicetoken;
    let dataObj = {
      "alert": 'hello',
      "uuid": uuid(),
      "sessionId": req.body.sessionId,
      "token": req.body.tokboxToken,
      "callerId": me.userCode,
      "callerName": me.nickName || me.name,
      "handle": "Show"
    }
    let dataStr = JSON.stringify(dataObj);
    let command = `curl -v -d \'${dataStr}\' --http2 --cert ${cert}:1234 ${appleURL}`;
    // let command = `curl -v -d \'${dataStr}\' --http2 --cert show_voip_cert.pem:1234 ${appleURL}`;
    me.tokbox.type = 1;
    me.save();
    console.log(command);
    try {
      //读取的是根目录下的cert文件
      if(isTest){
        let path = require('path')
        let localFile = path.join(appRoot, 'routes', 'apns.sh');
        if(shell.exec(localFile).code !== 0){
          // shell.echo('Error: command failed(test)');
          throw 'Error: command failed(test)'
        }
      }
      else if(shell.exec(command).code !== 0){
        // shell.echo('Error: command failed');
        throw 'Error: command failed'
      }
    }
    catch(e) {
      console.error(e)
    }

    res.json({errorCode: 1, message: 'Done'});

  }).catch(err => {
    console.log(err)
    res.json({errorCode: 0, message: err.message ? err.message : err});
  })

})

module.exports = router;
